<?php
class Psychologists extends CActiveRecord {
	public $uploadedImage;
	
	const AVATAR_WIDTH_L = 160;
	const AVATAR_HEIGHT_L = 120;
	const AVATAR_WIDTH_M = 100;
	const AVATAR_HEIGHT_M = 75;
	const AVATAR_SUFFIX_L = 'L';
	const AVATAR_SUFFIX_M = 'M';
	const AVATAR_EXT = '.jpg';

	public static function model($className = __CLASS__) {
		return parent::model($className);
	}

	public function tableName() {
		return strtolower('Psychologists');
	}

	public function rules() {
		return array(
			array('psychologistName, avatar', 'required'),
			array('psychologistQq', 'numerical')
		);	
	}

	public function defaultScope() {
		return array(
			'order' => 'sortOrder ASC'
		);
	}
	
	public function relations() {
		return array(
			'qqCode' => array(self::HAS_ONE, 'PsychologistsMeta', 'psychologistId',
				'condition' => 'metaKey = "'.PsychologistsMeta::KEY_QQCODE.'"'
			),
			'direction' => array(self::HAS_ONE, 'PsychologistsMeta', 'psychologistId',
				'condition' => 'metaKey = "'.PsychologistsMeta::KEY_DIRECTION.'"'
			)
		);
	}

//	public function safeAtrributes() {
//		
//	}
//	
//	public function relations() {
//		
//	}
	public function attributeLabels() {
		return array(
			'psychologistName' => '咨询师姓名',
			'avatar' => '头像'
		);
	}
	
	public function random() {
		$criteria = new CDbCriteria;
		$criteria->condition = 'isMajor = 1';
		$count = $this->count($criteria);
		$offset = mt_rand(0, $count-1);
		$criteria->offset = $offset;
		$criteria->limit = 1;
		return $this->find($criteria);
	}
	
	public static function avatarUrl($avatar, $suffix = self::AVATAR_SUFFIX_M) {
		$avatar = pathinfo($avatar, PATHINFO_FILENAME);
		$path = UPLOADS_PSY_AVATARS.'/'.$avatar.'_'.$suffix.self::AVATAR_EXT;
		$uri = Yii::app()->baseUrl.'/'.$path;
		return is_file($path) ? $uri : false;
	}
}
